package com.gz;

public class test_synchronized {
    public static void main(String[] args) {
        Thread001 thread001 = new Thread001();
        Thread thread1 = new Thread(thread001);
        thread1.setName("1号");
        Thread thread2= new Thread(thread001);
        thread2.setName("2号");
        Thread thread3 = new Thread(thread001);
        thread3.setName("3号");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class Thread001 implements Runnable {

    private int  money=10000;
    private boolean flag=true;
    public void run() {
        while (flag) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            withdraw();//这种方法以及下面这种方法都可以，但注意，这两种方法是非公平锁
            synchronized(this){
                if(money<=0){
                    System.out.println("余额不足");
                    flag=false;
                    return;
                }
                money-=1000;
                System.out.println(Thread.currentThread().getName()+"取走一次，还剩 "+money);
            }
        }
    }

//    public synchronized void withdraw(){
//                if(money<=0){
//                    System.out.println("余额不足");
//                    flag=false;
//                    return;
//                }
//                money-=1000;
//                            System.out.println(Thread.currentThread().getName()+"取走一次，还剩 "+money);
//    }

}